package com.kx.springsecurity.config;

import com.kx.springsecurity.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName MyWebConfig
 * @Author Sun
 * @Date 2021/5/25 20:01
 */
@EnableWebSecurity //启用spring security
@Configuration
public class MyWebConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserService myUserService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();//禁止跨域拦截
        http.authorizeRequests()//认证所有的请求
            .anyRequest()//除了单独设置的其他的任何请求
            .authenticated()//都需要认证
            .and().logout().logoutUrl("/logout")//设置 spring 提供好的退出地址的映射地址以及退出成功后去哪
            .permitAll()//放行
            .and().formLogin()//spring 连登陆地址和接口都写好了,我们只需要告诉它通过什么路径访问
            .loginProcessingUrl("/login")
            .permitAll();//放行

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(myUserService)//设置查询用户信息的 service
            .passwordEncoder(bCryptPasswordEncoder);//设置密码编码队形
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
